package com.happy3w.ssp.schoolmatehome.service.auth;

import com.happy3w.ssp.schoolmatehome.entity.User;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

public class TheUserDetail implements UserDetails {
    public static final String ANONYMOUS_NAME = "anonymous";
    public static final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS";
    public static final String ROLE_NAMED = "ROLE_NAMED";

    public static final TheUserDetail anonymous = buildAnonymous();

    @Getter
    private final User user;

    private final List<GrantedAuthority> authorities = new ArrayList<>();


    private TheUserDetail(User user, String...roles) {
        this.user = user;
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return "";
    }

    @Override
    public String getUsername() {
        return user.getName();
    }

    public static TheUserDetail buildNormal(User user) {
        return new TheUserDetail(user, ROLE_NAMED);
    }

    private static TheUserDetail buildAnonymous() {
        User user = User.builder()
                .id(0L)
                .name(ANONYMOUS_NAME)
                .avatar("")
                .enabled(true)
                .wxUnionId("-")
                .wxOpenId("-")
                .joinInAt(new Date())
                .createdAt(new Date())
                .updatedAt(new Date())
                .build();
        return new TheUserDetail(user, ROLE_ANONYMOUS);
    }
}
